package com.ruoyi.hospital.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.hospital.entity.*;
import com.ruoyi.hospital.entity.check.*;
import com.ruoyi.hospital.utils.AESUtils;
import com.ruoyi.hospital.utils.Base64Util;
import com.ruoyi.hospital.utils.MD5Util;
import com.ruoyi.hospital.utils.SignGenerator;
import com.ruoyi.service.domain.*;
import com.ruoyi.service.mapper.*;
import com.ruoyi.service.service.IServiceAppinfoService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

import static com.ruoyi.hospital.utils.SignGenerator.sortMap;
import static com.ruoyi.hospital.utils.phpSecret.phpSign;

@Component
public class HospitalCheckService {

    @Autowired
    private ServiceOrdersMapper ordersMapper;

    @Autowired
    private ServiceNurseMapper nurseMapper;

    @Autowired
    private ServiceMycartMapper mycartMapper;

    @Autowired
    private ServiceItemscomboMapper itemscomboMapper;

    @Autowired
    private ServiceComboMapper comboMapper;

    @Autowired
    private ServiceItemsMapper itemsMapper;

    @Autowired
    private ServiceAddressMapper addressMapper;

    @Autowired
    private ServicePayroadMapper payroadMapper;

    @Autowired
    private ServiceOrderscomboMapper orderscomboMapper;

    @Autowired
    private ServiceOrdersitemsMapper ordersitemsMapper;

    @Autowired
    private ServicePackagescomboMapper packagescomboMapper;

    @Autowired
    private ServicePackagesMapper packagesMapper;

    @Autowired
    private ServiceOrderspackagesMapper orderspackagesMapper;

    @Autowired
    private ServicePayMapper payMapper;

    @Autowired
    private ServiceAssessmentMapper assessmentMapper;

    @Autowired
    private ServicePictureMapper pictureMapper;

    @Autowired
    private ServiceCodeMapper codeMapper;

    @Autowired
    private ServiceRefuseMapper refuseMapper;

    @Autowired
    private ServiceCategoryitemsMapper categoryitemsMapper;

    @Autowired
    private ServiceTimeMapper timeMapper;

    @Autowired
    private ServiceActionMapper actionMapper;

    @Autowired
    private ServiceOrderotherpayMapper orderotherpayMapper;

    @Autowired
    private ServiceUsersMapper usersMapper;

    @Qualifier("hospitalRestTemplate")
    @Autowired
    private RestTemplate restTemplateHospital;

    @Autowired
    private IServiceAppinfoService appinfoService;

    @Autowired
    private ServiceMsginfoMapper msginfoMapper;

    @Autowired
    private ServiceUsermsgMapper usermsgMapper;

    public List<ServiceOrderscombo> getServiceOrderscomboList(Long orderId, String flag) {
        ServiceOrderscombo searchOrdersCombo = new ServiceOrderscombo();
        searchOrdersCombo.setOrderscomboOrderid(orderId);
        searchOrdersCombo.setOrderscomboUseFlag(flag); // 0原有 1新增
        searchOrdersCombo.setOrderscomboDelFlag("0");
        return orderscomboMapper.selectServiceOrderscomboList(searchOrdersCombo);
    }

    public List<ServiceOrdersitems> getServiceOrdersitemsList(Long orderId, String flag) {
        ServiceOrdersitems searchOrdersitems = new ServiceOrdersitems();
        searchOrdersitems.setOrdersitemsOrderid(orderId);
        searchOrdersitems.setOrdersitemsUseFlag(flag); // 0原有 1新增
        searchOrdersitems.setOrdersitemsDelFlag("0");
        return ordersitemsMapper.selectServiceOrdersitemsList(searchOrdersitems);
    }


    @Transactional
    public ServiceChargeVO getServiceCharge(Long orderId, LoginHospital oldHospital){

        ServiceChargeVO serviceChargeVO = new ServiceChargeVO();
        Long serviceChargePrice = 0L;
        Long differentPrice = 0L;
        List<ServiceChargeItem> serviceChargeItemList = new ArrayList<ServiceChargeItem>();
        List<ServiceOrderscombo> orderscomboList = getServiceOrderscomboList(orderId, null);
        List<ServiceOrdersitems> ordersitemsList = getServiceOrdersitemsList(orderId, null);

        if (orderscomboList != null && orderscomboList.size() > 0 ){
            for(ServiceOrderscombo orderscombo : orderscomboList){
                ServiceChargeItem serviceChargeItem = new ServiceChargeItem();

                ServiceCombo combo = comboMapper.selectServiceComboByComboIdNew(orderscombo.getOrderscomboComboid());
                if (combo == null) continue;
                serviceChargeItem.setComboId(combo.getComboId());
                serviceChargeItem.setComboName(combo.getComboName());
                serviceChargeItem.setCount(orderscombo.getOrderscomboCount());
                serviceChargeItem.setPrice(combo.getComboCurrentprice());
                serviceChargeItem.setNewFlag(Integer.parseInt(orderscombo.getOrderscomboUseFlag()));
                if("1".equals(orderscombo.getOrderscomboUseFlag())){
                    differentPrice += serviceChargeItem.getPrice();
                }
                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(orderscombo.getOrderscomboComboid());
                ServiceItems item = itemsMapper.selectServiceItemsByItemId(itemscombo.getItemscomboItemid());
                if (item != null) {
                    serviceChargeItem.setItemId(item.getItemId());
                    serviceChargeItem.setItemName(item.getItemName());
                    //serviceChargeItem.setPrice(item.getItemPrice());
                    serviceChargePrice = serviceChargePrice + serviceChargeItem.getPrice() * orderscombo.getOrderscomboCount();
                }

                serviceChargeItemList.add(serviceChargeItem);

            }

            serviceChargeVO.setServiceChargePrice(serviceChargePrice);
            serviceChargeVO.setDifferentPrice(differentPrice);
            serviceChargeVO.setServiceChargeItemList(serviceChargeItemList);

        }

        //OLD
        //if(ordersitemsList != null && ordersitemsList.size() > 0){
        //    for(ServiceOrdersitems ordersitems : ordersitemsList){
        //
        //        ServiceChargeItem serviceChargeItem = new ServiceChargeItem();
        //        ServiceItems item = itemsMapper.selectServiceItemsByItemIdNew(ordersitems.getOrdersitemsItemid());
        //        if (item == null) continue;
        //        serviceChargeItem.setItemId(item.getItemId());
        //        serviceChargeItem.setItemName(item.getItemName());
        //        serviceChargeItem.setPrice(item.getItemPrice());
        //
        //        ServiceItemscombo searchItemsCombo = new ServiceItemscombo();
        //        searchItemsCombo.setItemscomboItemid(ordersitems.getOrdersitemsItemid());
        //        if(orderscomboList != null && orderscomboList.size() > 0){
        //            for(ServiceOrderscombo orderscombo : orderscomboList){
        //                searchItemsCombo.setItemscomboSuppliesid(orderscombo.getOrderscomboComboid());
        //                searchItemsCombo.setItemscomboUseFlag("0");
        //                searchItemsCombo.setItemscomboDelFlag("0");
        //                List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectServiceItemscomboList(searchItemsCombo);
        //                if (itemscomboList != null && itemscomboList.size()>0){
        //                    for (ServiceItemscombo itemCombo : itemscomboList){
        //                        ServiceCombo combo = comboMapper.selectServiceComboByComboIdNew(itemCombo.getItemscomboSuppliesid());
        //                        if (combo == null) continue;
        //                        serviceChargeItem.setComboId(combo.getComboId());
        //                        serviceChargeItem.setComboName(combo.getComboName());
        //                        serviceChargeItem.setCount(orderscombo.getOrderscomboCount());
        //                        serviceChargeItem.setPrice(combo.getComboCurrentprice());
        //                        serviceChargeItem.setNewFlag(Integer.parseInt(orderscombo.getOrderscomboUseFlag()));
        //                        if("1".equals(orderscombo.getOrderscomboUseFlag())){
        //                            differentPrice += serviceChargeItem.getPrice();
        //                        }
        //                        serviceChargePrice = serviceChargePrice + serviceChargeItem.getPrice() * ordersitems.getOrdersitemsCount();
        //                        serviceChargeItemList.add(serviceChargeItem);
        //                    }
        //                }
        //            }
        //        }
        //        serviceChargeVO.setServiceChargePrice(serviceChargePrice);
        //        serviceChargeVO.setDifferentPrice(differentPrice);
        //        serviceChargeVO.setServiceChargeItemList(serviceChargeItemList);
        //    }
        //}
        return serviceChargeVO;
    }

    @Transactional
    public PackageChargeVO getPackageCharge(Long orderId, LoginHospital oldHospital){
        PackageChargeVO packageChargeVO = new PackageChargeVO();
        Long packageChargePrice = 0L;
        Long differentPrice = 0L;
        List<PackageChargeItem> packageChargeItemList = new ArrayList<PackageChargeItem>();
        ServiceOrderspackages searchOrdersPackages = new ServiceOrderspackages();
        searchOrdersPackages.setOrderspackagesOrderid(orderId);
        searchOrdersPackages.setOrderspackagesDelFlag("0");
        List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(searchOrdersPackages);
        if(orderspackagesList != null && orderspackagesList.size() > 0){
            for(ServiceOrderspackages orderspackages : orderspackagesList){
                PackageChargeItem packageChargeItem = new PackageChargeItem();
                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(orderspackages.getOrderspackagesPackageid());
                packageChargeItem.setPackageId(packages.getPackagesId());
                packageChargeItem.setPackageName(packages.getPackagesName());
                packageChargeItem.setCount(orderspackages.getOrderspackagesCount());
                packageChargeItem.setPrice(packages.getPackagesPrice());
                packageChargeItem.setNewFlag(Integer.parseInt(orderspackages.getOrderspackagesUseFlag()));
                packageChargePrice = packageChargePrice + packageChargeItem.getPrice() * orderspackages.getOrderspackagesCount();
                if ("1".equals(orderspackages.getOrderspackagesUseFlag())){
                    differentPrice += packageChargeItem.getPrice();
                }
                packageChargeItemList.add(packageChargeItem);
            }
        }
        packageChargeVO.setSuppliesChargePrice(packageChargePrice);
        packageChargeVO.setSuppliesChargeItemList(packageChargeItemList);
        packageChargeVO.setDifferentPrice(differentPrice);


        return packageChargeVO;
    }

    @Transactional
    public TravelChargeVO getTravelCharge(Long orderId, LoginHospital oldHospital){

        TravelChargeVO travelChargeVO = new TravelChargeVO();
        ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
        ServiceAddress address = addressMapper.selectServiceAddressByAddressId(orders.getOrderAddressid());
        travelChargeVO.setAddressId(address.getAddressId());
        travelChargeVO.setAddressInfo(address.getAddressInfo());
        travelChargeVO.setAddressDetail(address.getAddressDetail());

        ServicePayroad searchPayroad = new ServicePayroad();
        searchPayroad.setPayroadOrderid(orderId);
        searchPayroad.setPayroadUseFlag("0");
        searchPayroad.setPayroadDelFlag("0");
        List<ServicePayroad> payroadList = payroadMapper.selectServicePayroadList(searchPayroad);
        if(payroadList != null && payroadList.size() > 0){
            for(ServicePayroad payroad : payroadList){
                travelChargeVO.setPayroadId(payroad.getPayroadId());
                travelChargeVO.setAdvancePrice(payroad.getPayroadAdvancepay());
                if(payroad.getPayroadActualpay() != null && payroad.getPayroadBill() != null){
                    travelChargeVO.setTravelChargePrice(payroad.getPayroadActualpay() + payroad.getPayroadBill());
                }else{
                    travelChargeVO.setTravelChargePrice(payroad.getPayroadAdvancepay());
                }
                travelChargeVO.setBillPrice(payroad.getPayroadBill());
                travelChargeVO.setActualPrice(payroad.getPayroadActualpay());

            }
        }
        return travelChargeVO;
    }

    @Transactional
    public List<PictureReturn> getHospitalPicture(Long orderId, LoginHospital oldHospital){
        List<PictureReturn> retPictures = new ArrayList<PictureReturn>();

        ServicePicture searchPicture = new ServicePicture();
        searchPicture.setPictureOrderid(orderId);
        searchPicture.setPictureType("2");
        searchPicture.setPictureDelFlag("0");
        List<ServicePicture> pictures = pictureMapper.selectServicePictureList(searchPicture);
        for (ServicePicture picture : pictures) {
            PictureReturn hospitalPictureBody = new PictureReturn();
            hospitalPictureBody.setPictureId(picture.getPictureId());
            hospitalPictureBody.setPicturePic(picture.getPicturePic());
            retPictures.add(hospitalPictureBody);
        }

        return retPictures;
    }

    @Transactional
    public boolean uploadHospitalPicture(HospitalPictureRequest pictureBody , LoginHospital oldHospital)
    {
        try {
            ServicePicture newPicture = new ServicePicture();
            newPicture.setPictureOrderid(pictureBody.getOrderId());
            newPicture.setPictureType("2");//账单说明
            newPicture.setPictureDelFlag("0");
            List<ServicePicture> oldPictures = pictureMapper.selectServicePictureList(newPicture);
            if(oldPictures != null && oldPictures.size() > 7){
                throw new Exception("上传数量超过上限");
            }
            newPicture.setPictureUserid(oldHospital.getUserId());
            newPicture.setPictureCreateBy(oldHospital.getUsername());
            newPicture.setPictureCreateTime(new Date());
            newPicture.setPictureUpdateBy(oldHospital.getUsername());
            newPicture.setPictureUpdateTime(new Date());

            List<String> imgUrls = pictureBody.getImgUrls();
            for (String imgUrl : imgUrls){
                newPicture.setPicturePic(imgUrl);
                newPicture.setPictureRemark(pictureBody.getRemark());
                pictureMapper.insertServicePicture(newPicture);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean deleteHospitalPicture(HospitalPictureRequest pictureBody , LoginHospital oldHospital)
    {
        try {
            ServicePicture newPicture = new ServicePicture();
            List<String> imgUrls = pictureBody.getImgUrls();
            for (String imgUrl : imgUrls){
                newPicture.setPictureOrderid(pictureBody.getOrderId());
                newPicture.setPicturePic(imgUrl);
                newPicture.setPictureType("2");//账单说明
                newPicture.setPictureDelFlag("2");
                pictureMapper.deleteByUrl(newPicture);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public HospitalBillVO getHospitalCharge(Long orderId, LoginHospital oldHospital){

        HospitalBillVO hospitalBillVO = new HospitalBillVO();
        ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
        ServicePay pay = payMapper.selectServicePayByPayId(orders.getOrderPay());
        hospitalBillVO.setOrderId(orderId);
        hospitalBillVO.setAdvanceMoney(pay.getPayAdvancepay());
        hospitalBillVO.setBill(pay.getPayBill());

        if (pay.getPayActualpay() != null) hospitalBillVO.setActualMoney(pay.getPayActualpay());
        if (pay.getPayDifference() != null) hospitalBillVO.setDifferenceMoney(pay.getPayDifference());

        return hospitalBillVO;
    }

    @Transactional
    public CheckInfoRsp getOrderCheckInfo(Long orderId, LoginHospital oldHospital){
        CheckInfoRsp checkInfoRsp = new CheckInfoRsp();
        ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
        checkInfoRsp.init(orders);

        List<ServiceTime> timeList = timeMapper.selectServiceTimeByOrderId(orderId);
        for (ServiceTime time : timeList){
            if( time.getTimeAction().equals("33")){
                DateFormat cstFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String finishTime = cstFormate.format(time.getTimeTime());
                checkInfoRsp.setOrderFinishTime(finishTime);
                break;
            }
        }
        ServiceChargeVO serviceCharge = getServiceCharge(orderId, oldHospital);
        CheckServiceInfo checkServiceInfo = new CheckServiceInfo();
        checkServiceInfo.init(serviceCharge);
        checkInfoRsp.setServiceInfo(checkServiceInfo);

        PackageChargeVO packageCharge = getPackageCharge(orderId, oldHospital);
        CheckConsumeInfo checkConsumeInfo = new CheckConsumeInfo();
        checkConsumeInfo.init(packageCharge);
        checkInfoRsp.setConsumeInfo(checkConsumeInfo);

        List<ServiceOrderotherpay> orderotherpayList = orderotherpayMapper.selectOtherpayByOrderId(orderId);
        CheckOthersInfo checkOthersInfo = new CheckOthersInfo();
        checkOthersInfo.init(orderotherpayList);
        checkInfoRsp.setOthersInfo(checkOthersInfo);

        TravelChargeVO travelCharge = getTravelCharge(orderId, oldHospital);
        CheckTaxiInfo checkTaxiInfo = new CheckTaxiInfo();
        checkTaxiInfo.init(travelCharge);
        checkInfoRsp.setTaxiInfo(checkTaxiInfo);

        List<ServicePicture> pictures = pictureMapper.selectCheckListByOrderId(orderId);
        CheckNurProofs checkNurProofs = new CheckNurProofs();
        List<ServicePicture> remarks = pictureMapper.selectRemarkListByOrderId(orderId);
        checkNurProofs.init(pictures, remarks);
        checkInfoRsp.setNurProofs(checkNurProofs);

        HospitalBillVO hospitalCharge = getHospitalCharge(orderId, oldHospital);
        CheckPrepaidAmount checkPrepaidAmount = new CheckPrepaidAmount();
        checkPrepaidAmount.init(hospitalCharge, travelCharge);
        checkInfoRsp.setPrepaidAmount(checkPrepaidAmount);

        CheckSettlement checkSettlement = new CheckSettlement();
        checkSettlement.setActualTotalAmount(checkServiceInfo.getServiceCharge() + checkConsumeInfo.getConsumeCharge() + checkOthersInfo.getOthersCharge() + checkTaxiInfo.getActualAmount());
        checkSettlement.setDifferenceAmount(checkSettlement.getActualTotalAmount() - checkPrepaidAmount.getTotalAmount());
        if (orders.getOrderServiceflag() >= 12){
            checkSettlement.setIsSettled(true);
        }
        for (ServiceTime time : timeList){
            if( time.getTimeAction().equals("30") ){
                DateFormat cstFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String settleTime = cstFormate.format(time.getTimeTime());
                checkSettlement.setSettleTime(settleTime);
                break;
            }
        }
        checkInfoRsp.setSettlement(checkSettlement);

        return checkInfoRsp;
    }

    //新增套餐
    public boolean addCheckCombo(Long comboId, Long itemId, Long orderId, Long count, LoginHospital oldHospital){
        try {
            ServiceOrderscombo orderscombo = new ServiceOrderscombo();
            orderscombo.setOrderscomboOrderid(orderId);
            orderscombo.setOrderscomboComboid(comboId);
            List<ServiceOrderscombo> newOrdersCombo = orderscomboMapper.selectByOrderIdAndComboIdNew(orderscombo);
            if( newOrdersCombo.size() > 0){
                orderscombo = newOrdersCombo.get(0);
            }
            orderscombo.setOrderscomboOrderid(orderId);
            orderscombo.setOrderscomboComboid(comboId);
            orderscombo.setOrderscomboCount(count);
            orderscombo.setOrderscomboUpdateBy(oldHospital.getUsername());
            orderscombo.setOrderscomboUpdateTime(new Date());

            orderscombo.setOrderscomboUseFlag("1");
            if( newOrdersCombo.size() > 0){
                orderscomboMapper.updateServiceOrderscombo(orderscombo);
            }else{
                orderscombo.setOrderscomboCreateBy(oldHospital.getUsername());
                orderscombo.setOrderscomboCreateTime(new Date());
                orderscomboMapper.insertServiceOrderscombo(orderscombo);
            }


            if ( newOrdersCombo.size() == 0){
                ServiceOrdersitems newOrdersItem = new ServiceOrdersitems();
                newOrdersItem.setOrdersitemsItemid(itemId);
                newOrdersItem.setOrdersitemsCount(count);
                newOrdersItem.setOrdersitemsOrderid(orderId);
                newOrdersItem.setOrdersitemsCreateBy(oldHospital.getUsername());
                newOrdersItem.setOrdersitemsCreateTime(new Date());
                newOrdersItem.setOrdersitemsUpdateBy(oldHospital.getUsername());
                newOrdersItem.setOrdersitemsUpdateTime(new Date());
                newOrdersItem.setOrdersitemsUseFlag("1");
                ordersitemsMapper.insertServiceOrdersitems(newOrdersItem);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    //修改新增套餐
    public boolean updateCheckCombo(Long comboId, Long itemId, Long orderId, Long count, LoginHospital oldHospital){
        try {

            ServiceOrderscombo orderscombo = new ServiceOrderscombo();
            orderscombo.setOrderscomboOrderid(orderId);
            orderscombo.setOrderscomboComboid(comboId);
            List<ServiceOrderscombo> newOrdersCombo = orderscomboMapper.selectByOrderIdAndComboIdNew(orderscombo);
            if( newOrdersCombo.size() > 0){
                orderscombo = newOrdersCombo.get(0);
            }else{
                return false;
            }
            if (count == 0){
                orderscombo.setOrderscomboDelFlag("2");
                //deleteOrdersItems(comboId, orderId, oldHospital);
            }
            orderscombo.setOrderscomboCount(count);
            orderscombo.setOrderscomboUpdateBy(oldHospital.getUsername());
            orderscombo.setOrderscomboUpdateTime(new Date());

            orderscomboMapper.updateServiceOrderscombo(orderscombo);

            if (count == 0 ){
                int flag = 0;
                ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(comboId);
                List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectByItemId(itemscombo.getItemscomboItemid());
                for(ServiceItemscombo itemCombo : itemscomboList){
                    ServiceOrderscombo searchLast = new ServiceOrderscombo();
                    searchLast.setOrderscomboOrderid(orderId);
                    searchLast.setOrderscomboComboid(itemCombo.getItemscomboSuppliesid());
                    List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectByOrderIdAndComboId(searchLast);
                    if (orderscomboList.size() > 0){
                        flag = 1;
                        break;
                    }
                }
                if( flag == 0){
                    ServiceOrdersitems ordersitems = new ServiceOrdersitems();
                    ordersitems.setOrdersitemsOrderid(orderId);
                    ordersitems.setOrdersitemsItemid(itemId);
                    ordersitems.setOrdersitemsDelFlag("2");
                    ordersitems.setOrdersitemsUpdateBy(oldHospital.getUsername());
                    ordersitems.setOrdersitemsUpdateTime(new Date());
                    ordersitemsMapper.updateServiceOrdersitems(ordersitems);
                }
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    //public boolean deleteOrdersItems(Long comboId, Long orderId, LoginHospital oldHospital){
    //    try {
    //        ServiceItemscombo itemscombo = itemscomboMapper.selectByComboId(comboId);
    //        ServiceOrdersitems ordersitems = new ServiceOrdersitems();
    //        ordersitems.setOrdersitemsOrderid(orderId);
    //        ordersitems.setOrdersitemsItemid(itemscombo.getItemscomboItemid());
    //        ordersitems.setOrdersitemsUseFlag("1");
    //        ordersitems.setOrdersitemsDelFlag("0");
    //        List<ServiceOrdersitems> ordersitemsList = ordersitemsMapper.selectServiceOrdersitemsList(ordersitems);
    //        ordersitems.setOrdersitemsUpdateBy(oldHospital.getUsername());
    //        ordersitems.setOrdersitemsUpdateTime(new Date());
    //
    //        ordersitemsMapper.updateServiceOrdersitems(ordersitems);
    //    }catch (Exception e){
    //        return false;
    //    }
    //    return true;
    //}

    //新增耗材包
    public boolean addCheckPackage(Long orderId, List<AddPkgNodeReq> packageBody, LoginHospital oldHospital){
        try {

            ServiceOrderspackages orderspackages = new ServiceOrderspackages();
            orderspackages.setOrderspackagesOrderid(orderId);
            for (AddPkgNodeReq packageBodyItem : packageBody){
                Long packageId = packageBodyItem.getPkgId();
                Long count = packageBodyItem.getNum();
                orderspackages.setOrderspackagesPackageid(packageId);
                List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectByOrderIdAndPackageIdNew(orderspackages);

                if( orderspackagesList.size() > 0){
                    orderspackages = orderspackagesList.get(0);
                    orderspackages.setOrderspackagesCount((orderspackages.getOrderspackagesCount() + count));
                }else{
                    orderspackages.setOrderspackagesCount(count);
                }
                orderspackages.setOrderspackagesUpdateBy(oldHospital.getUsername());
                orderspackages.setOrderspackagesUpdateTime(new Date());
                orderspackages.setOrderspackagesUseFlag("1");
                if( orderspackagesList.size() > 0){
                    orderspackagesMapper.updateServiceOrderspackages(orderspackages);
                }else{
                    orderspackages.setOrderspackagesCreateBy(oldHospital.getUsername());
                    orderspackages.setOrderspackagesCreateTime(new Date());
                    orderspackagesMapper.insertServiceOrderspackages(orderspackages);

                }

            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    //修改新增的耗材包
    public boolean updateCheckPackage(Long packageId, Long orderId, Long count, LoginHospital oldHospital){
        try {
            ServiceOrderspackages orderspackages = new ServiceOrderspackages();
            orderspackages.setOrderspackagesOrderid(orderId);
            orderspackages.setOrderspackagesPackageid(packageId);
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectByOrderIdAndPackageIdNew(orderspackages);
            if (orderspackagesList.size() == 0){
                return false;
            }else{
                orderspackages = orderspackagesList.get(0);
            }
            if (count == 0){
                orderspackages.setOrderspackagesDelFlag("2");
            }else{
                orderspackages.setOrderspackagesCount(count);
            }
            orderspackages.setOrderspackagesUpdateBy(oldHospital.getUsername());
            orderspackages.setOrderspackagesUpdateTime(new Date());

            orderspackagesMapper.updateServiceOrderspackages(orderspackages);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    
    ///套餐列表查询
    public Page<CheckItemsListReturnVO> getCategoryItemsListWithPagination(int page, int size) {
        List<ItemsListReturnVO> itemsList = new ArrayList<>();
        List<CheckItemsListReturnVO> retList = new ArrayList<CheckItemsListReturnVO>();
        ServiceCategoryitems serviceCategoryitems = new ServiceCategoryitems();
        //serviceCategoryitems.setCategoryitemsCategoryid(1L);
        serviceCategoryitems.setCategoryitemsUseFlag("0");
        serviceCategoryitems.setCategoryitemsDelFlag("0");
        List<ServiceCategoryitems> categoryitemsList = categoryitemsMapper.selectServiceCategoryitemsList(serviceCategoryitems);

        for (ServiceCategoryitems item : categoryitemsList) {
            ServiceItems itemNode = itemsMapper.selectServiceItemsByItemId(item.getCategoryitemsItemid());
            ItemsListReturnVO itemsCombosNode = new ItemsListReturnVO(itemNode);
            CheckItemsListReturnVO retNode = new CheckItemsListReturnVO();

            ServiceItemscombo itemsComboSearch = new ServiceItemscombo();
            itemsComboSearch.setItemscomboUseFlag("0");
            itemsComboSearch.setItemscomboDelFlag("0");
            itemsComboSearch.setItemscomboItemid(itemNode.getItemId());
            List<ServiceItemscombo> itemscomboList = itemscomboMapper.selectServiceItemscomboList(itemsComboSearch);

            for (ServiceItemscombo itemCombo : itemscomboList) {
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(itemCombo.getItemscomboSuppliesid());

                if (itemsCombosNode.getCombos() == null) {
                    itemsCombosNode.setCombos(new ArrayList<ServiceCombo>());
                }
                itemsCombosNode.getCombos().add(combo);
            }
            retNode.init(itemsCombosNode);
            retList.add(retNode);
            itemsList.add(itemsCombosNode);

        }

        // 分页逻辑
        Pageable pageable = PageRequest.of(page, size);
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), retList.size());
        List<CheckItemsListReturnVO> pagedItemsList = retList.subList(start, end);

        return new PageImpl<>(pagedItemsList, pageable, retList.size());
    }

    ///耗材包列表查询
    public Page<CheckPackageRsp> getComboPackagesListWithPagination(Long orderId, int page, int size, LoginHospital oldHospital) {
        List<ComboPackageReturnHospital> itemsList = new ArrayList<>();
        List<CheckPackageRsp> retList = new ArrayList<CheckPackageRsp>();
        List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
        for (ServiceOrderscombo orderscombo : orderscomboList){
            Long comboId = orderscombo.getOrderscomboComboid();
            ServiceCombo combo = comboMapper.selectServiceComboByComboId(comboId);
            ServicePackagescombo packagescombo = new ServicePackagescombo();
            packagescombo.setPackagescomboComboid(comboId);
            List<ServicePackagescombo> packagescomboList = packagescomboMapper.selectServicePackagescomboList(packagescombo);
            ComboPackageReturnHospital newNode = new ComboPackageReturnHospital();
            CheckPackageRsp retNode = new CheckPackageRsp();
            newNode.setCombo(combo);
            for (ServicePackagescombo item : packagescomboList) {
                ServicePackages packages = packagesMapper.selectServicePackagesByPackagesId(item.getPackagescomboPackagesid());
                if (newNode.getPackages() == null) {
                    newNode.setPackages(new ArrayList<ServicePackages>());
                }
                newNode.getPackages().add(packages);
            }
            retNode.init(newNode);
            retList.add(retNode);
            itemsList.add(newNode);

        }




        // 分页逻辑
        Pageable pageable = PageRequest.of(page, size);
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), retList.size());
        List<CheckPackageRsp> pagedItemsList = retList.subList(start, end);

        return new PageImpl<>(pagedItemsList, pageable, retList.size());
    }

    static CategoryListReturnVO findChildren(CategoryListReturnVO category, List<CategoryListReturnVO> categoryList) {
        for (CategoryListReturnVO item : categoryList) {
            if (category.getCategoryId().equals(item.getCategoryLink())) {
                if (category.getChildren() == null) {
                    category.setChildren(new ArrayList<CategoryListReturnVO>());
                }
                category.getChildren().add(findChildren(item, categoryList));
            }
        }
        return category;
    }
    //取消按钮
    public boolean cancelAddNew(Long orderId, LoginHospital oldHospital){
        try {
            ServiceOrderspackages orderspackages = new ServiceOrderspackages();
            orderspackages.setOrderspackagesOrderid(orderId);
            orderspackages.setOrderspackagesUseFlag("1");
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(orderspackages);
            for (ServiceOrderspackages node : orderspackagesList) {
                node.setOrderspackagesOrderid(orderId);
                node.setOrderspackagesDelFlag("2");
                node.setOrderspackagesUpdateBy(oldHospital.getUsername());
                node.setOrderspackagesUpdateTime(new Date());

                orderspackagesMapper.updateServiceOrderspackages(node);
            }

            ServiceOrderscombo orderscombo = new ServiceOrderscombo();
            orderscombo.setOrderscomboOrderid(orderId);
            orderscombo.setOrderscomboUseFlag("1");
            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboList(orderscombo);
            for (ServiceOrderscombo node : orderscomboList) {
                node.setOrderscomboOrderid(orderId);
                node.setOrderscomboDelFlag("2");
                node.setOrderscomboUpdateBy(oldHospital.getUsername());
                node.setOrderscomboUpdateTime(new Date());
                orderscomboMapper.updateServiceOrderscombo(node);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }
    //保存按钮
    public boolean saveAddNew(Long orderId, LoginHospital oldHospital){
        try {
            ServiceOrderspackages orderspackages = new ServiceOrderspackages();
            orderspackages.setOrderspackagesOrderid(orderId);
            orderspackages.setOrderspackagesUseFlag("1");
            List<ServiceOrderspackages> orderspackagesList = orderspackagesMapper.selectServiceOrderspackagesList(orderspackages);
            for (ServiceOrderspackages node : orderspackagesList) {
                node.setOrderspackagesOrderid(orderId);
                node.setOrderspackagesUseFlag("0");
                node.setOrderspackagesUpdateBy(oldHospital.getUsername());
                node.setOrderspackagesUpdateTime(new Date());

                orderspackagesMapper.updateServiceOrderspackages(node);
            }

            ServiceOrderscombo orderscombo = new ServiceOrderscombo();
            orderscombo.setOrderscomboOrderid(orderId);
            orderscombo.setOrderscomboUseFlag("1");
            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboList(orderscombo);
            for (ServiceOrderscombo node : orderscomboList) {
                node.setOrderscomboOrderid(orderId);
                node.setOrderscomboUseFlag("0");
                node.setOrderscomboUpdateBy(oldHospital.getUsername());
                node.setOrderscomboUpdateTime(new Date());
                orderscomboMapper.updateServiceOrderscombo(node);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }
    //提交结算
    public boolean checkOrders(Long orderId, Long goPay, Long backPay, String remark, LoginHospital oldHospital){
        try {

            //saveAddNew(orderId, oldHospital);
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServicePayroad payroad = payroadMapper.selectServicePayroadByOrderId(orderId);
            payroad.setPayroadBill(goPay);
            payroad.setPayroadActualpay(backPay);
            payroad.setPayroadDifference( goPay + backPay - payroad.getPayroadAdvancepay());
            payroad.setPayroadUpdateBy(oldHospital.getUsername());
            payroad.setPayroadUpdateTime(new Date());
            payroadMapper.updateServicePayroad(payroad);

            ServicePay pay = payMapper.selectServicePayByPayId(orders.getOrderPay());
            CheckInfoRsp orderCheckInfo = getOrderCheckInfo(orderId, oldHospital);
            Long comboPay = orderCheckInfo.getServiceInfo().getServiceCharge();
            Long packagePay = orderCheckInfo.getConsumeInfo().getConsumeCharge();
            pay.setPayActualpay(comboPay + packagePay);
            pay.setPayDifference(pay.getPayAdvancepay() - pay.getPayActualpay());
            pay.setPayUpdateBy(oldHospital.getUsername());
            pay.setPayUpdateTime(new Date());
            payMapper.updateServicePay(pay);

            orders.setOrderServiceflag(12);
            orders.setOrderUpdateBy(oldHospital.getUsername());
            orders.setOrderUpdateTime(new Date());

            ordersMapper.updateServiceOrders(orders);
            ServicePicture picture = new ServicePicture();
            picture.setPictureRemark(remark);
            picture.setPictureOrderid(orderId);
            picture.setPictureUserid(orders.getOrderUserid());
            picture.setPictureType("3");
            picture.setPictureCreateBy(oldHospital.getUsername());
            picture.setPictureCreateTime(new Date());
            picture.setPictureUpdateBy(oldHospital.getUsername());
            picture.setPictureUpdateTime(new Date());

            pictureMapper.insertServicePicture(picture);
            addOrderProcess(orderId);

            ServicePay oldPay = payMapper.selectServicePayByPayId(orders.getOrderPay());
            ServiceOrders order = ordersMapper.selectServiceOrdersByOrderId(orderId);
            Long diff = (oldPay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) - (oldPay.getPayActualpay() + payroad.getPayroadBill() + payroad.getPayroadActualpay());
            if(diff > 0){
                ServiceUsers users = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());

                String token_url = "https://hlwyy.ldqyylzx.cn/dhccam/token/generate?grant_type=api_credentials";

                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", base64("a785cf74-de42-6905-2b2f-15ec02d376e9:34fb7fa64f43031419434c211ac48217"));

                Map<String, String> paramMap = new HashMap<>();
                HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
                System.out.println(httpEntity);
                ResponseEntity<Object> response = restTemplateHospital.postForEntity(token_url, httpEntity, Object.class);
                Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
                String token = (String) responseBody.get("access_token");

                String gateway_url = "https://hlwyy.ldqyylzx.cn/dhccam/gateway/index";
                Map<String, Object> dataPay = new HashMap<String, Object>();
                dataPay.put("transactionId", pay.getPayAdvancepaytype());
                //dataPay.put("orgRefundOrder", pay.getPayAdvancepaycode());
                dataPay.put("totalFee", ((float)(pay.getPayAdvancepay() + payroad.getPayroadAdvancepay()) /100) + "");
                dataPay.put("refundFee", ((float)diff / 100) + "");
                dataPay.put("memo", "partRefund");
                //dataPay.put("patientId", users.getUsersId());
                //dataPay.put("uid", users.getUsersOpenid());
                dataPay.put("timestamp", Instant.now().getEpochSecond());//todo 可能是大写
                String signPay = phpSign("cspAVFPPuv2eWpShAekNnaCJXXrU5R28", dataPay);
                dataPay.put("sign", signPay);

                Map<String, Object> payObjectMap = buildMapHl( dataPay, "paycenter.paygateway.refund", "body", token);
                //unifiedEntity = new HttpEntity<>(stringObjectMap, headers);

                headers = new HttpHeaders();
                headers.set("content-type", "application/json");

                HttpEntity<Map<String, Object>> httpEntityPay = new HttpEntity<>(payObjectMap, headers);
                System.out.println(httpEntityPay);
                ResponseEntity<Object> refundPayInfo = restTemplateHospital.postForEntity(gateway_url, httpEntityPay, Object.class);

                Map<String, Object> refundPayInfoBody = (Map<String, Object>) refundPayInfo.getBody();
                String refundDataOld = (String) refundPayInfoBody.get("data");
                String refundData = AESUtils.Decrypt(refundDataOld);
                JSONObject refundObject = new JSONObject(refundData);
                Integer code = refundObject.getInt("code");
                String refundOrderNo = refundObject.getString("refundOrderNo");
                String refundId = refundObject.getString("refundId");


                if (code != 0){
                    return false;
                }
                ServicePay newPay = new ServicePay();
                //退款完成订单接口
                newPay.setPayId(orders.getOrderPay());
                newPay.setPayFinalpay(oldPay.getPayActualpay());
                newPay.setPayFinalpaycode(refundOrderNo);
                newPay.setPayFinalpaytype(refundId);

                newPay.setPayActualpay(oldPay.getPayActualpay());

                newPay.setPayStatusfinish("2");
                newPay.setPayUpdateBy(oldHospital.getUsername());
                newPay.setPayUpdateTime(new Date());
                payMapper.updateServicePay(newPay);

                ServiceOrders newOrder = new ServiceOrders();
                newOrder.setOrderServiceflag(14);
                newOrder.setOrderServiceflag(15);
                newOrder.setOrderId(orderId);
                newOrder.setOrderUpdateBy(oldHospital.getUsername());
                newOrder.setOrderUpdateTime(new Date());
                ordersMapper.updateServiceOrders(newOrder);

            }
            if(diff == 0) {
                ServicePay newPay = new ServicePay();
                //退款完成订单接口
                newPay.setPayId(orders.getOrderPay());
                newPay.setPayFinalpay(oldPay.getPayActualpay());
                newPay.setPayFinalpaycode("");
                newPay.setPayFinalpaytype("");

                newPay.setPayActualpay(oldPay.getPayActualpay());

                newPay.setPayStatusfinish("0");
                newPay.setPayUpdateBy(oldHospital.getUsername());
                newPay.setPayUpdateTime(new Date());
                payMapper.updateServicePay(newPay);

                ServiceOrders newOrder = new ServiceOrders();
                newOrder.setOrderServiceflag(14);
                newOrder.setOrderServiceflag(15);
                newOrder.setOrderId(orderId);
                newOrder.setOrderUpdateBy(oldHospital.getUsername());
                newOrder.setOrderUpdateTime(new Date());
                ordersMapper.updateServiceOrders(newOrder);
            }
            addOrderProcess(orderId);

            if (diff < 0){
                ServiceUsers users = usersMapper.selectServiceUsersByUsersId(order.getOrderUserid());
                ServiceMsginfo msginfo = msginfoMapper.selectServiceMsginfoByMsg("补缴提醒");
                List<ServiceUsermsg> usermsgList = usermsgMapper.selectServiceUsermsgByUserId(orders.getOrderUserid());
                if (usermsgList == null) return true;
                Boolean notifyflag = false;
                for (ServiceUsermsg usermsg : usermsgList){
                    if (usermsg.getUsermsgMsginfoid().equals(msginfo.getMsginfoId())){
                        if ("0".equals(usermsg.getUsermsgUseFlag())){
                            notifyflag = true;
                            break;
                        }else{
                            return true;
                        }
                    }
                }
                if (!notifyflag) return true;

                List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
                String retDesc = "";
                for (ServiceOrderscombo orderscombo : orderscomboList){
                    ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                    if (combo == null) continue;
                    retDesc += combo.getComboName() + "(" + orderscombo.getOrderscomboCount() + "份);";
                    break;
                }
                retDesc += "...";
                ServiceAppinfo appinfo = appinfoService.selectServiceAppinfoByAppinfoId(4L);

                // 获取token
                String notify_token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appinfo.getAppinfoAppid(), appinfo.getAppinfoSecret());
                com.alibaba.fastjson2.JSONObject tokenInfo = JSON.parseObject(HttpUtil.get(notify_token_url));
                String accessToken = tokenInfo.getString("access_token");
                // 使用前端code获取手机号码 参数为json格式
                //String url = "https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token=" + tokenInfo.getString("access_token");
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + tokenInfo.getString("access_token");
                Map<String, Object> notifyParamMap = new HashMap<>();
                notifyParamMap.put("template_id", msginfo.getMsginfoValue());
                notifyParamMap.put("page", "/pages/patOrder/patOrderDetail?orderId="+orderId);
                notifyParamMap.put("touser", users.getUsersOpenid());

                Map<String, Object> data = new HashMap<>();
                Map<String, Object> thing6 = new HashMap<>();
                Map<String, Object> amount5 = new HashMap<>();
                Map<String, Object> thing7 = new HashMap<>();
                thing6.put("value", "差价补缴提醒");
                amount5.put("value", (float)((-diff) / 100));
                thing7.put("value", "订单实际费用大于预付");

                data.put("thing6", thing6);
                data.put("amount5", amount5);
                data.put("thing7", thing7);

                notifyParamMap.put("data", data);
                notifyParamMap.put("miniprogram_state", "developer");
                notifyParamMap.put("lang", "zh_CN");
                HttpHeaders notifyHeaders = new HttpHeaders();
                HttpEntity<Map<String, Object>> notifyHttpEntity = new HttpEntity<>(notifyParamMap, notifyHeaders);
                System.out.println(notifyHttpEntity);
                ResponseEntity<Object> notifyResponse = restTemplateHospital.postForEntity(url, notifyHttpEntity, Object.class);

                String body = String.valueOf(notifyResponse.getBody());// 解析JSON字符串
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    public static Map<String, Object> buildMapHl(Object data, String method, String key, String token) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> bizContent = new HashMap<String, Object>();

        bizContent.put(key, data);
        map.put("token_type", "api_credentials");
        map.put("version", "v1.0");
        map.put("nonce_str", new Random().nextInt(10000));
        map.put("biz_content", bizContent);
        map.put("method", method);
        map.put("app_id", "a785cf74-de42-6905-2b2f-15ec02d376e9");

        //String token = getToken(ConstantUtil.GET_TOKEN_URL,"a785cf74-de42-6905-2b2f-15ec02d376e9", "34fb7fa64f43031419434c211ac48217");
        map.put("token", token);

        // 没有配置加密，不需要计算
        // 没有配置sign，不需要计算
        SignGenerator.buildSign(map, "prod_doc_sign_16", "MD5");
        String ss = JSONUtils.toJSONString(bizContent).replace("/", "\\/");
        map.put("biz_content", AESUtils.Encrypt(ss));
        return map;
    }

    public static void  buildSign(Map<String, Object> map, String security, String encodeType) {
        Map<String, Object> signMap = new HashMap<String, Object>();
        signMap.putAll(map);
        HashMap<String, Object> biz = (HashMap<String, Object>) signMap.get("biz_content");
        for (String key :biz.keySet()) {
            String value = null;
            if (biz.get(key) instanceof String) {
                value = (String) biz.get(key);
            } else {
                value = JSONUtils.toJSONString(biz.get(key));
            }
            signMap.put(key, value);
        }
        signMap.remove("biz_content");
        if ("MD5".equals(encodeType)) {
            List<Map.Entry<String, Object>> params = sortMap(signMap);
            StringBuilder sign = new StringBuilder();
            for (int i = 0; i < params.size(); i++) {
                if (!StringUtils.isEmpty(sign.toString())) {
                    sign.append("&");
                }
                sign.append(params.get(i).getKey()).append("=").append(params.get(i).getValue());
            }

            sign.append(security);
            //System.out.println("sign=====" + sign.toString());

            String md5Str = MD5Util.md5(sign.toString()).toUpperCase();;
            map.put("sign", md5Str);
        }

    }

    private String base64(String input) {
        // 实现base64编码逻辑
        return Base64Util.base64(input);
    }

    @Transactional
    public Boolean addOrderProcess(Long orderId){
        try {
            ServiceOrders orders = ordersMapper.selectServiceOrdersByOrderId(orderId);
            ServiceTime newTime = new ServiceTime();
            String process = "noNotify";

            newTime.setTimeOrderid(orderId);
            newTime.setTimeTime(new Date());

            Integer flag = orders.getOrderServiceflag();
            switch (flag){
                case 1:
                    newTime.setTimeAction("提交订单");
                    newTime.setTimeActionid(1L);
                    break;
                case 2:
                    newTime.setTimeAction("取消订单");
                    newTime.setTimeActionid(13L);
                    if (orders.getOrderPay() != null){
                        process = "订单取消";
                    }
                    break;
                case 3:
                    newTime.setTimeAction("支付订单");
                    newTime.setTimeActionid(2L);
                    break;
                case 4:
                    newTime.setTimeAction("订单退款");
                    newTime.setTimeActionid(4L);
                    if (orders.getOrderPay() == null){
                        process = "订单取消";
                    }else{
                        process = "订单已退款";
                    }
                    break;
                case 5:
                    newTime.setTimeAction("护理部接单");
                    newTime.setTimeActionid(27L);
                    break;
                case 6:
                case 7:
                    newTime.setTimeAction("已分配");
                    newTime.setTimeActionid(23L);
                    process = "已分配护士";
                    break;
                case 8:
                    newTime.setTimeAction("待服务");
                    newTime.setTimeActionid(24L);
                    process = "护士已接单";
                    break;
                case 9:
                    newTime.setTimeAction("已出发");
                    newTime.setTimeActionid(9L);
                    process = "护士已出发";
                    break;
                case 10:
                    newTime.setTimeAction("服务中");
                    newTime.setTimeActionid(10L);
                    process = "护士已到达";
                    break;
                case 11:
                    newTime.setTimeAction("服务完成");
                    newTime.setTimeActionid(33L);
                    process = "服务完成";
                    break;
                case 12:
                    newTime.setTimeAction("费用核定");
                    newTime.setTimeActionid(30L);
                    break;
                case 13:
                    newTime.setTimeAction("用户确认");
                    newTime.setTimeActionid(35L);
                    break;
                case 14:
                    newTime.setTimeAction("最终支付");
                    newTime.setTimeActionid(36L);
                    process = "最终结算完成";
                    break;
                case 15:
                case 16:
                case 17:
                    newTime.setTimeAction("已完成");
                    newTime.setTimeActionid(37L);
                    process = "订单完成";
                    break;
            }

            if (timeMapper.insertServiceTime(newTime) == 1){
                if(orders.getOrderServiceflag() == 14){
                    newTime.setTimeAction("已完成");
                    newTime.setTimeActionid(37L);
                    timeMapper.insertServiceTime(newTime);
                }
                //return true;
            }
            if (process.equals("noNotify")){
                return true;
            }
            ServiceUsers users = usersMapper.selectServiceUsersByUsersId(orders.getOrderUserid());
            ServiceMsginfo msginfo = msginfoMapper.selectServiceMsginfoByMsg("订单状态");
            List<ServiceUsermsg> usermsgList = usermsgMapper.selectServiceUsermsgByUserId(orders.getOrderUserid());
            if (usermsgList == null) return true;
            Boolean notifyflag = false;
            for (ServiceUsermsg usermsg : usermsgList){
                if (usermsg.getUsermsgMsginfoid().equals(msginfo.getMsginfoId())){
                    if ("0".equals(usermsg.getUsermsgUseFlag())){
                        notifyflag = true;
                        break;
                    }else{
                        return true;
                    }
                }
            }
            if (!notifyflag) return true;

            List<ServiceOrderscombo> orderscomboList = orderscomboMapper.selectServiceOrderscomboByOrderId(orderId);
            String retDesc = "";
            for (ServiceOrderscombo orderscombo : orderscomboList){
                ServiceCombo combo = comboMapper.selectServiceComboByComboId(orderscombo.getOrderscomboComboid());
                if (combo == null) continue;
                retDesc += combo.getComboName() + "(" + orderscombo.getOrderscomboCount() + "份);";
                break;
            }
            retDesc += "...";
            ServiceAppinfo appinfo = appinfoService.selectServiceAppinfoByAppinfoId(4L);

            // 获取token
            String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appinfo.getAppinfoAppid(), appinfo.getAppinfoSecret());
            com.alibaba.fastjson2.JSONObject tokenInfo = JSON.parseObject(HttpUtil.get(token_url));
            String accessToken = tokenInfo.getString("access_token");
            // 使用前端code获取手机号码 参数为json格式
            //String url = "https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + tokenInfo.getString("access_token");
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("template_id", msginfo.getMsginfoValue());
            paramMap.put("page", "/pages/patOrder/patOrderDetail?orderId="+orderId);
            paramMap.put("touser", users.getUsersOpenid());

            Map<String, Object> data = new HashMap<>();
            Map<String, Object> thing5 = new HashMap<>();
            thing5.put("value", process);
            Map<String, Object> thing1 = new HashMap<>();
            thing1.put("value", retDesc);
            data.put("thing5", thing5);
            data.put("thing1", thing1);
            paramMap.put("data", data);
            paramMap.put("miniprogram_state", "developer");
            paramMap.put("lang", "zh_CN");
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            System.out.println(httpEntity);
            ResponseEntity<Object> response = restTemplateHospital.postForEntity(url, httpEntity, Object.class);

            String body = String.valueOf(response.getBody());// 解析JSON字符串

        }catch (Exception e){
            return false;
        }
        return false;
    }

    //其他费用
    public Long addOthers(Long orderId, String desc, Long price, Long count, LoginHospital oldHospital){
        try {
            ServiceOrderotherpay orderotherpay = new ServiceOrderotherpay();
            orderotherpay.setOrderotherpayOrderid(orderId);
            orderotherpay.setOrderotherpayDesc(desc);
            orderotherpay.setOrderotherpayPrice(price);
            orderotherpay.setOrderotherpayCount(count);
            orderotherpay.setOrderotherpayCreateBy(oldHospital.getUsername());
            orderotherpay.setOrderotherpayCreateTime(new Date());
            orderotherpay.setOrderotherpayUpdateBy(oldHospital.getUsername());
            orderotherpay.setOrderotherpayUpdateTime(new Date());

            orderotherpayMapper.insertServiceOrderotherpay(orderotherpay);
            return orderotherpay.getOrderotherpayId();

        }catch (Exception e){
            return null;
        }

    }

    public Boolean delOthers(Long orderId, Long otherId, LoginHospital oldHospital){
        try {
            ServiceOrderotherpay orderotherpay = new ServiceOrderotherpay();
            //orderotherpay.setOrderotherpayOrderid(orderId);
            orderotherpay.setOrderotherpayId(otherId);
            orderotherpay.setOrderotherpayUpdateBy(oldHospital.getUsername());
            orderotherpay.setOrderotherpayUpdateTime(new Date());
            orderotherpay.setOrderotherpayDelFlag("2");

            orderotherpayMapper.updateServiceOrderotherpay(orderotherpay);
            return true;

        }catch (Exception e){
            return false;
        }

    }

}
